package com.yuecai.modules.order;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.yuecai.modules.yc_brand.service.YcBrandService;
import com.yuecai.exception.BadRequestException;
import com.yuecai.modules.yc_order.service.OrderService;
import com.yuecai.modules.yc_order.service.dto.OrderDto;
import com.yuecai.modules.yc_order.service.dto.SubmitOrderDto;
import com.yuecai.modules.yc_order.service.dto.YcOrderDto;
import com.yuecai.modules.yc_order.service.dto.YcOrderQueryCriteria;
import com.yuecai.modules.yc_order.service.factory.OrderFactory;
import com.yuecai.modules.yc_order.service.impl.BuyNowService;
import com.yuecai.modules.yc_order.service.impl.ShoppingCartService;
import com.yuecai.modules.yc_order.service.impl.YcOrderService;
import com.yuecai.modules.yc_user.service.YcUserService;
import com.yuecai.modules.yc_user.service.dto.YcUserDto;
import com.yuecai.modules.yc_user.service.dto.YcUserQueryCriteria;
import com.yuecai.utils.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.List;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping("/api/order")
public class OrderController {


    @Autowired
    private YcOrderService ycOrderService;
    @Autowired
    private YcUserService ycUserService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private BuyNowService buyNowService;

    @PostConstruct
    public void initOrderService(){
        OrderFactory.register(1,buyNowService);
        OrderFactory.register(2,shoppingCartService);
    }
    /**
     * 填写订单
     * @param dto
     * @return
     */
    @PostMapping("/write-order")
    public ResponseEntity<Object> writeOrder(@RequestBody OrderDto dto) throws Exception {

        OrderService orderService = OrderFactory.getOrderServiceByType(dto.getType());
        return orderService.writeOrder(dto);
    }


    /**
     * 查询价格
     * @return
     */
    @PostMapping("/showPrice")
    public ResponseEntity<Object> findOrder(@RequestBody SubmitOrderDto dto) throws Exception {
        OrderService orderService = OrderFactory.getOrderServiceByType(dto.getType());
        return orderService.showPrice(dto);
    }

    /**
     * 提交订单
     * @param dto
     * @return
     */
    @PostMapping("/submit-order")
    public ResponseEntity<Object> submitOrder(@Validated @RequestBody  SubmitOrderDto dto) throws Exception {

        OrderService orderService = OrderFactory.getOrderServiceByType(dto.getType());
        System.out.println(orderService.hashCode()+"-------"+shoppingCartService.hashCode());
        try {
            return orderService.submitOrder(dto);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /*
    信息不全，只返回了订单列表，APP端调用 findOrder
    @GetMapping
    @ApiOperation("查询order")
    public ResponseEntity<Object> query(YcOrderQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(ycOrderService.queryAll(criteria,pageable),HttpStatus.OK);
    }*/

    /**
     * 查询订单
     * @return
     */
    @GetMapping("/find-order/{orderSn}")
    public ResponseEntity<Object> findOrder(@PathVariable String orderSn){

        return ycOrderService.findByOrderSn(orderSn);
    }


    /**
     * 查询订单
     * @return
     */
    @GetMapping("/find-order")
    public ResponseEntity<Object> findOrder(YcOrderQueryCriteria criteria,Pageable pageable) throws JsonProcessingException {

        String currentUsername = SecurityUtils.getCurrentUsername();
        Long aLong = Long.valueOf(currentUsername);
        criteria.setUserId(aLong);
        return ycOrderService.query(criteria,pageable);

    }
    /**
     * 取消订单
     * @return
     */
    @PutMapping("/cancel")
    public ResponseEntity<Object> cancelOrder(@RequestBody String orderSn) throws Exception {

        return ycOrderService.cancelOrder(orderSn);
    }


    /**
     * 收货
     * @return
     */
    @PutMapping("/delivery")
    public ResponseEntity<Object> deliveryOrder(@RequestBody String orderSn) throws Exception {

        return ycOrderService.deliveryOrder(orderSn);
    }



    /**
     * 司机查看订单
     * @return
     */
    @GetMapping("/sj")
    public ResponseEntity<Object> sjFindOrder() {
        String currentUsername = SecurityUtils.getCurrentUsername();
        Long aLong = Long.valueOf(currentUsername);
        YcUserDto byId = ycUserService.findById(aLong);
        if (byId.getType()!=2){
            return new ResponseEntity<>("您的身份不是配送人员,不能获取数据！",HttpStatus.BAD_REQUEST);
        }
        return ycOrderService.sjFindOrder(aLong);
    }


    /**
     * 业务员查看订单
     * lengsong
     * @return
     */
    @GetMapping("/yw")
    public ResponseEntity<Object> ywFindOrder(YcOrderQueryCriteria criteria,Pageable pageable) {
        String currentUsername = SecurityUtils.getCurrentUsername();
        Long aLong = Long.valueOf(currentUsername);
        YcUserDto byId = ycUserService.findById(aLong);
        if (byId.getType()!=3){
            return new ResponseEntity<>("您的身份不是业务员,不能获取数据！",HttpStatus.BAD_REQUEST);
        }
        Long pid = 100029L;
        //Long pid = byId.getPid();
        if (pid == null){
            return new ResponseEntity<>("没有订单！",HttpStatus.OK);
        }
        YcUserQueryCriteria ycUserQueryCriteria = new YcUserQueryCriteria();
        //ycUserQueryCriteria.setPid(Long.valueOf(pid));
        ycUserQueryCriteria.setPid(pid);
        List<YcUserDto> userDtoList = ycUserService.queryAll(ycUserQueryCriteria);
        YcOrderQueryCriteria ycOrderQueryCriteria = new YcOrderQueryCriteria();
        List<Timestamp> time = new ArrayList<>();
        if (criteria.getDate() == 1){
            Timestamp todayStart = new Timestamp(getStartTime().getTime());
            Timestamp todayEnd = new Timestamp(getEndTime().getTime());
            time.add(todayStart);
            time.add(todayEnd);
            ycOrderQueryCriteria.setCreateTime(time);
        }
        if (criteria.getDate() == 2){
            Timestamp monthStart = new Timestamp(getTimesMonthmorning().getTime());
            Timestamp monthEnd = new Timestamp(getTimesMonthnight().getTime());
            time.add(monthStart);
            time.add(monthEnd);
            ycOrderQueryCriteria.setCreateTime(time);
        }
        Set<Long> userIds = new HashSet<>();
        for (YcUserDto item : userDtoList){
            userIds.add(item.getId());
        }
        ycOrderQueryCriteria.setUserIds(userIds);
        //Map<String,Object> orderList = ycOrderService.queryAllPage(ycOrderQueryCriteria,pageable);
        //List<YcOrderDto> orderList = ycOrderService.queryAllPage(ycOrderQueryCriteria);
        return ycOrderService.ywFindOrder(ycOrderQueryCriteria,pageable,userIds.size());
    }

    private static Date getStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime();
    }
    private static Date getEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }
    // 获得本月第一天0点时间
    public static Date getTimesMonthmorning() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        return cal.getTime();
    }


    // 获得本月最后一天24点时间
    public static Date getTimesMonthnight() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.HOUR_OF_DAY, 24);
        return cal.getTime();
    }
}
